<?php

namespace app\models;

use Yii;
use yii\base\Model;

class RegForm extends Model
{
    public $username;
    public $password;
    public $nick_name; // 假设需要显示名
    public $dn; // 假设需要这个字段

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            ['password','string','min' => 6, 'tooShort' => '密码长度至少为6位'],
            ['username', 'unique', 'targetClass' => User::class, 'message' => '该用户名已被占用'],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function reg()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->username = $this->username;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->nick_name = $this->nick_name;

        if ($user->save()) {
            return $user;
        }
        return null;
    }
}